package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.base.BaseResult;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.model.CreditRepay;
import com.cardbaobao.cardbabyclient.model.Event;
import com.cardbaobao.cardbabyclient.model.MemberInfo;
import com.cardbaobao.cardbabyclient.model.UserBindCards;
import com.cardbaobao.cardbabyclient.model.result.CreditRepayResult;
import com.cardbaobao.cardbabyclient.model.result.UserBindCardsResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.dialog.UnbindCardDialog;
import com.cardbaobao.cardbabyclient.ui.pop.CustomPopWin;
import com.cardbaobao.cardbabyclient.ui.pop.NumberKeyInputPwdPop;
import com.cardbaobao.cardbabyclient.ui.pop.RepayNumberKeyBoardPop;
import com.cardbaobao.cardbabyclient.ui.pop.RepaymentPop;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Description:
 * Created by FHW
 * on 2017/11/7
 */

public class NewRepaymentActivity extends BaseActivity {

    private static final int TYPE_ADD_CARD = 1;//添加储蓄卡
    private static final int TYPE_REPLACE_CARD = 2;//更换储蓄卡

    @BindView(R.id.title_bar)
    TitleBar title_bar;

    @BindView(R.id.iv_icon)
    CircleImageView iv_icon;
    @BindView(R.id.tv_bank_name)
    TextView tv_bank_name;
    @BindView(R.id.tv_name)
    TextView tv_name;

    @BindView(R.id.et_amount)
    EditText et_amount;
    @BindView(R.id.rl_del)
    RelativeLayout rl_del;
    @BindView(R.id.bt_ensure_commit)
    Button bt_ensure_commit;

    private CustomPopWin popwin;
    private RepayNumberKeyBoardPop pop;
    private StringBuilder sb;

    private String repay_money = "";

    private RepaymentPop repaymentPop;
    private List<UserBindCards.DebitCard> debitCards;
    private NumberKeyInputPwdPop popInputPwd;

    private boolean loading = false;

    private String userName = "";
    private String bankName = "";
    private String cardNumber = "";
    private String picUrl = "";
    private String cardId = "";

    private DecimalFormat df = new DecimalFormat("#0.00");

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_repayment;
    }

    @OnClick({R.id.et_amount, R.id.rl_del, R.id.bt_ensure_commit})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.et_amount:
                showPopKeyboard();
                break;
            case R.id.rl_del:
                et_amount.setText("");
                break;
            case R.id.bt_ensure_commit:
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_repay_confirm,
                        Self.Action.app_click_repayment_repay_confirm_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }
                showPopRepayment();
                break;
        }
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        EventBus.getDefault().register(this);

        mCurrentPageId = Self.Page.app_repayment_repay;

        title_bar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title_bar.setRightViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopView();
            }
        });

        debitCards = new ArrayList<>();

        userName = getIntent().getStringExtra("userName");
        bankName = getIntent().getStringExtra("bankName");
        cardNumber = getIntent().getStringExtra("cardNumber");
        picUrl = getIntent().getStringExtra("picUrl");
        cardId = getIntent().getStringExtra("cardId");

        ImageLoaderUtil.displayImage(URLUtil.CBB_IMG_URL + picUrl, iv_icon);
        tv_bank_name.setText(bankName);
        tv_name.setText(userName + "（尾号" + cardNumber.substring(cardNumber.length() - 4, cardNumber.length()) + "）");

        //处理输入框光标
        try {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod(
                    "setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(et_amount, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        et_amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                repay_money = s.toString();
                if (repay_money.equals("")) {
                    rl_del.setVisibility(View.INVISIBLE);
                    bt_ensure_commit.setEnabled(false);
                } else {
                    rl_del.setVisibility(View.VISIBLE);
                    bt_ensure_commit.setEnabled(true);
                    //判断输入金额是否合理
                    double inputAmount = Double.parseDouble(repay_money);
                    if (inputAmount > 20000) {
                        ToastUtil.showToastLong("单笔还款金额不能超过20000元");
                        sb.delete(0, sb.length());
                        sb.append("20000");
                        et_amount.setText(sb.toString());
                    }

                }
            }
        });

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        loadData(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void showPopView() {
        final View popView = LayoutInflater.from(this).inflate(R.layout.pop_credit_repayment, null, false);

        LinearLayout ll_bank_dot = (LinearLayout) popView.findViewById(R.id.ll_bank_dot);
        LinearLayout ll_unbound = (LinearLayout) popView.findViewById(R.id.ll_unbound);
        TextView tv_recording = (TextView) popView.findViewById(R.id.tv_recording);
        TextView tv_loan = (TextView) popView.findViewById(R.id.tv_loan);
        TextView tv_bank_dot = (TextView) popView.findViewById(R.id.tv_bank_dot);
        TextView tv_use_help = (TextView) popView.findViewById(R.id.tv_use_help);
        TextView tv_unbound = (TextView) popView.findViewById(R.id.tv_unbound);

        ll_bank_dot.setVisibility(View.VISIBLE);
        ll_unbound.setVisibility(View.VISIBLE);

        if (popwin == null) {
            popwin = new CustomPopWin(this, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.8f);
        }

        popwin.setFocusable(true);
        popwin.setContentView(popView);
        popwin.showAsDropDown(title_bar, 0, 0, Gravity.RIGHT);

        tv_recording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_credit_card_repay_record,
                        Self.Action.app_click_repayment_credit_card_repay_record_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                Intent intent = new Intent();
                intent.setClass(NewRepaymentActivity.this, RepaymentRecordActivity.class);
                intent.putExtra("credit_card_no", cardNumber);
                intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                startActivity(intent);
                popwin.dismiss();
            }
        });
        tv_loan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_credit_card_cash_loan,
                        Self.Action.app_click_repayment_credit_card_cash_loan_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri content_url = Uri.parse(URLUtil.CASH_LOAN);
                intent.setData(content_url);
                startActivity(intent);
                popwin.dismiss();
            }
        });
        ll_bank_dot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popwin.dismiss();
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_credit_card_banks_show,
                        Self.Action.app_click_repayment_credit_card_banks_show_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                Intent intent = new Intent();
                intent.setClass(NewRepaymentActivity.this, FindBankActivity.class);
                intent.putExtra("bankName", bankName);
                intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                startActivity(intent);
            }
        });
        tv_use_help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popwin.dismiss();
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_credit_card_usage_help,
                        Self.Action.app_click_repayment_credit_card_usage_help_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                initIntent();
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, "信用卡还款常见问题");
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S, URLUtil.USE_HELP_AGREEMENT);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 13);
                mIntent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                startActivity(mIntent);
            }
        });
        ll_unbound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_credit_card_unbind_cards,
                        Self.Action.app_click_repayment_credit_card_unbind_cards_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                showUnBindDialog(bankName, cardNumber);
            }
        });

    }

    //解绑储蓄卡对话框
    private void showUnBindDialog(String cardName, final String debitCardNo) {
        final UnbindCardDialog dialog = new UnbindCardDialog(this, "您正在解绑--" + cardName + "信用卡(" + debitCardNo.substring(debitCardNo.length() - 4) + ")");
        dialog.setClickedListener(new UnbindCardDialog.ClickedListener() {
            @Override
            public void onEnsureClicked() {
                dialog.dismiss();
                unBoundCredit();
            }
        });
        dialog.show();
    }

    private void showPopKeyboard() {
        if (pop == null) {
            pop = new RepayNumberKeyBoardPop(mContext);
            pop.setNumberKeyListener(new RepayNumberKeyBoardPop.OnKeyPressed() {
                @Override
                public void onKeyPressed(int key) {
                    if (sb == null) {
                        sb = new StringBuilder();
                    } else {
                        sb.delete(0, sb.length());
                    }
                    sb.append(et_amount.getText().toString());
                    switch (key) {
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_FINISH:
                            //完成
                            pop.dismiss();

                            break;
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_DELETE:
                            //删除键
                            if (sb.length() > 0) {
                                sb.deleteCharAt(sb.length() - 1);
                            }
                            break;
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_ONE:
                            //数字键1
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_TWO:
                            //数字键2
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_THREE:
                            //数字键3
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_FOUR:
                            //数字键4
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_FIVE:
                            //数字键5
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_SIX:
                            //数字键6
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_SEVEN:
                            //数字键7
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_EIGHT:
                            //数字键8
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_NINE:
                            //数字键9
                            String str = sb.toString();
                            if (str.contains(".")) {
                                //精确到小数点后两位
                                int index = str.indexOf('.');
                                if (str.length() - index - 1 < 2) {
                                    sb.append(key);
                                }
                            } else {
                                sb.append(key);
                            }
                            break;
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_ZERO:
                            //数字键0
                            String text = sb.toString();
                            //精确到小数点后2位
                            if (text.length() > 0) {
                                if (text.contains(".")) {
                                    int index = text.indexOf('.');
                                    if (text.length() - index - 1 < 2) {
                                        sb.append(key);
                                    }
                                } else {
                                    if (!text.startsWith("0")) {
                                        sb.append(key);
                                    }
                                }
                            }
                            break;
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_DOT:
                            //小数点
                            if (!sb.toString().contains(".")) {
                                if (sb.length() != 0) {
                                    sb.append(".");
                                }
                            }
                            break;
                    }

                    //限制输入字符数
                    if (sb.length() > 8) {
                        et_amount.setText(sb.substring(0, 8));
                    } else {
                        et_amount.setText(sb.toString());
                    }

                    try {
                        et_amount.setSelection(et_amount.getText().length());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!pop.isShowing()) {
            pop.showAtLocation(et_amount, Gravity.BOTTOM, 0, 0);
        }
    }

    /**
     * 还款弹窗
     */
    private void showPopRepayment() {
        repaymentPop = new RepaymentPop(NewRepaymentActivity.this, debitCards) {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.iv_question:
//                        repaymentPop.dismiss();
                        initIntent();
                        mIntent.setClass(mContext, AgreementWebViewActivity.class);
                        mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, "信用卡还款常见问题");
                        mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S, URLUtil.USE_HELP_AGREEMENT);
                        mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 13);
                        startActivity(mIntent);
                        break;
                    case R.id.tv_determine://确定
                        if (debitCards != null && debitCards.size() > 1) {//已绑卡
                            SelfUtils.buriedClickData(Self.Action.app_click_repayment_repay_pay_confirm,
                                    Self.Action.app_click_repayment_repay_pay_confirm_des,
                                    mEnterPageTime,
                                    mCurrentPageId,
                                    mPrePageId);
                            queryRepay();
                        } else {//没绑卡
//                            repaymentPop.dismiss();
//                            loadRealNameInfo(TYPE_ADD_CARD);
                        }
                        break;
                }
            }

        };
        repaymentPop.setRepaymentCallBack(new RepaymentPop.RepaymentCallBack() {
            @Override
            public void onItemClick(int position) {
                if (debitCards != null && debitCards.size() > 1) {
                    if (position == (debitCards.size() - 1)) {//更换银行卡
//                        repaymentPop.dismiss();
                        loadRealNameInfo(TYPE_REPLACE_CARD);
                    } else {//所选银行
                        String str = debitCards.get(position).getDebit_card_no();
                        repaymentPop.setRepayBank(debitCards.get(position).getDebit_card_name() + "储蓄卡（" + str.substring(str.length() - 4, str.length()) + "）");
                    }
                } else {//没绑卡
//                    repaymentPop.dismiss();
                    loadRealNameInfo(TYPE_ADD_CARD);
                }
            }
        });
        if (!repay_money.equals("")) {
            repaymentPop.setMoney("¥ " + df.format(Double.parseDouble(repay_money)));
        }
        repaymentPop.setCreditCard(bankName + "（尾号" + cardNumber.substring(cardNumber.length() - 4, cardNumber.length()) + "）");
        if (debitCards != null && debitCards.size() > 1) {
            String str = debitCards.get(0).getDebit_card_no();
            repaymentPop.setRepayBank(debitCards.get(0).getDebit_card_name() + "储蓄卡（" + str.substring(str.length() - 4, str.length()) + "）");
        }
        if (!repaymentPop.isShowing()) {
            repaymentPop.showAtLocation(bt_ensure_commit, Gravity.NO_GRAVITY, 0, 0);
        }
    }

    /**
     * 输入密码
     */
    private void showNumKeyInputPop() {
        if (popInputPwd == null) {
            popInputPwd = new NumberKeyInputPwdPop(this);
            popInputPwd.setNumberKeyListener(new NumberKeyInputPwdPop.OnKeyFinish() {
                @Override
                public void onKeyFinish(String tranKey) {
                    if (!tranKey.equals("")) {//完成密码
                        verifyRepayPwd(tranKey);
                    } else {//忘记密码
                        toRepaymenPwdView(mContext, 1);
//                        popInputPwd.dismiss();
                    }
                }
            });

        }
        if (!popInputPwd.isShowing()) {
            popInputPwd.showAtLocation(et_amount, Gravity.NO_GRAVITY, 0, 0);
        }
    }

    /**
     * 验证支付密码
     */
    private void verifyRepayPwd(String pwd) {
        showProgressDialog(false);
        Api.verifyRepayPwd(String.valueOf(mApplication.getUser().getID()), pwd)
//        Api.verifyRepayPwd("5001766", pwd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_data_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        CreditRepayResult baseResult = JsonUtil.json2Object(s, CreditRepayResult.class);
                        if (baseResult.getCode() == Constant.SUC_CODE) {//成功
                            popInputPwd.hidErrorView();
                            popInputPwd.dismiss();
                            creditRepayment();
                        } else if (baseResult.getCode() == 2) {//验证失败
                            dismissProgressDialog();
                            if (!baseResult.getData().getNumber().equals("")) {
                                ToastUtil.showToast("支付密码输入错误，请重新输入");
                                popInputPwd.setErrorText(baseResult.getData().getNumber());
                                popInputPwd.cleanNum();
                            }
                        } else {//其他问题
                            dismissProgressDialog();
                            ToastUtil.showToast(baseResult.getMsg());
                            popInputPwd.hidErrorView();
                            popInputPwd.cleanNum();
                        }
                    }
                })
        ;
    }

    /**
     * 去 设置或修改支付密码
     *
     * @param mContext
     * @param value
     */
    private void toRepaymenPwdView(Context mContext, int value) {
        Intent intent = new Intent();
        intent.setClass(mContext, RepaymentPwdOneActivity.class);
        intent.putExtra("type", value);
        intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
        startActivityForResult(intent, Constant.REQUST_CODE);
    }

    //获取实名认证信息
    private void loadRealNameInfo(final int type) {
        showProgressDialog(false);
        Api.getMemberInfo(mApplication.getUser().getID()).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        BaseResult result = JsonUtil.json2Object(s, BaseResult.class);
                        if (result.getCode() == Constant.SUC_CODE) {
                            Object data = result.getData();
                            if (data instanceof JSONObject) {
                                JSONObject json = (JSONObject) data;
                                MemberInfo info = JsonUtil.json2Object(json.getJSONObject("MemberInfo").toJSONString(),
                                        MemberInfo.class);
                                if (info != null) {
                                    String name = info.getTrueName();
                                    String idCardNo = info.getIDCardNo();
                                    if (TextUtils.isEmpty(name) || TextUtils.isEmpty(idCardNo)) {
                                        //未实名认证
                                        Intent intent = new Intent();
                                        intent.setClass(mContext, IdentifyVerifyActivity.class);
                                        intent.putExtra(BankCardVerifyActivity.PAGE_FROM_I, BankCardVerifyActivity.ACTIVITY_REPAYMENT);
                                        intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                                        startActivity(intent);
                                    } else {
                                        //已实名认证
                                        Intent intent = new Intent();
                                        intent.putExtra(IdentifyVerifyActivity.NAME_S, name);
                                        intent.putExtra(IdentifyVerifyActivity.ID_CARD_NO_S, idCardNo);
                                        if (type == TYPE_ADD_CARD) {
                                            intent.setClass(mContext, IdentifyVerifyActivity.class);
                                            intent.putExtra(BankCardVerifyActivity.PAGE_FROM_I,
                                                    BankCardVerifyActivity.ACTIVITY_REPAYMENT);
                                            intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                                        } else {
                                            intent.setClass(mContext, ReplaceCardActivity.class);
                                        }
                                        startActivity(intent);
                                    }
                                } else {
                                    ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                            getString(R.string.string_data_exception));
                                }
                            }
                        } else {
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    /**
     * 获取储蓄卡
     */
    public void loadData(final boolean isShowPop) {
        showProgressDialog(false);
        Api.getUserBindCards(String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_data_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        UserBindCardsResult result = JsonUtil.json2Object(s, UserBindCardsResult.class);
                        if (result.getCode() == Constant.SUC_CODE) {
                            UserBindCards cards = result.getData();
                            if (cards != null) {
                                debitCards.clear();
                                //储蓄卡
                                for (int i = 0; i < cards.getDebitCardList().size(); i++) {
                                    if (i == 0) {
                                        cards.getDebitCardList().get(i).setChoose(true);
                                    }
                                }
                                debitCards.addAll(cards.getDebitCardList());
                                debitCards.add(debitCards.size(), new UserBindCards.DebitCard());

                                if (isShowPop) {
                                    if (repaymentPop != null && repaymentPop.isShowing()) {
                                        repaymentPop.dismiss();
                                    }
                                    showPopRepayment();
                                }

                            }
                        } else {
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }


    /**
     * 查询是否设置支付密码
     */
    private void queryRepay() {
        showProgressDialog(false);
        Api.queryRepayPwd(String.valueOf(mApplication.getUser().getID()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_data_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        BaseResult baseResult = JsonUtil.json2Object(s, BaseResult.class);
                        if (baseResult.getCode() == Constant.SUC_CODE) {//已设置支付密码
                            repaymentPop.dismiss();
                            showNumKeyInputPop();
                        } else if (baseResult.getCode() == 2) {//未设置支付密码
//                            repaymentPop.dismiss();
                            ToastUtil.showToast("请设置支付密码");
                            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    toRepaymenPwdView(mContext, 0);
                                }
                            },Constant.ONE_SECOND);
                        } else {
                            ToastUtil.showToast(baseResult.getMsg());
                        }
                    }
                });
    }

    /**
     * 代扣
     */
    public void creditRepayment() {
        if (loading) {
            return;
        }
        loading = true;
//        Api.creditRepayment("5001787", repay_money, cardId)
        Api.creditRepayment(String.valueOf(mApplication.getUser().getID()), repay_money, cardId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        loading = false;
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_data_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        loading = false;
                        CreditRepayResult creditRepayResult = JsonUtil.json2Object(s, CreditRepayResult.class);
                        Intent intent = new Intent();
                        intent.setClass(mContext, RepayResultActivity.class);
                        CreditRepay creditRepay = creditRepayResult.getData();
                        if (creditRepayResult.getCode() == Constant.SUC_CODE) {
                            intent.putExtra("state", creditRepay.getState());
                            intent.putExtra("remark1", creditRepay.getRemark1());
                            intent.putExtra("remark2", creditRepay.getRemark2());
                            intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                            if (!creditRepay.getState().equals("还款失败")) {
                                intent.putExtra("money", repay_money);
                                intent.putExtra("userName", userName);
                                intent.putExtra("bankName", bankName);
                                intent.putExtra("cardNumber", cardNumber);
                            }
                        } else {
//                            ToastUtil.showToast(creditRepayResult.getMsg());
                            intent.putExtra("state", "还款失败");
                            intent.putExtra("remark1", creditRepayResult.getMsg());
                        }
                        startActivity(intent);
                        if (creditRepayResult.getCode() == Constant.SUC_CODE && !"还款失败".equals(creditRepay.getState())) {
                            finish();
                        }
                    }
                });
    }


    /**
     * 解除还款卡绑定
     */
    private void unBoundCredit() {
        showProgressDialog(false);
        Api.unBoundCredit(String.valueOf(mApplication.getUser().getID()), cardNumber)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_data_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        BaseResult baseResult = JsonUtil.json2Object(s, BaseResult.class);
                        if (baseResult.getCode() == Constant.SUC_CODE) {//
                            popwin.dismiss();
                            ToastUtil.showToast("解绑成功");
                            finish();
                        } else {
                            ToastUtil.showToast(baseResult.getMsg());
                        }
                    }
                });
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == Constant.REQUST_CODE) {
//            switch (resultCode) {
//                case Constant.RESULT_CODE://设置支付密码回来
//                    if (repaymentPop != null && repaymentPop.isShowing()) {
//                        repaymentPop.dismiss();
//                    }
//                    showNumKeyInputPop();
//                    break;
//            }
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBindCardSuc(Event.BindCardRepaySuc bindCardRepaySuc) {
        loadData(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRepayPwdSuc(Event.SetRepayPwdSuc setRepayPwdSuc) {
        if (repaymentPop != null && repaymentPop.isShowing()) {
            repaymentPop.dismiss();
        }
        showNumKeyInputPop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
